// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import { syncCode } from './syncCode';
import { componentCompile } from './componentCompile';
import { prebuildDownload } from './prebuildDownload';
import { downloadImage } from './downloadImage';
import { deleteImage } from './deleteImage';
import path from 'path';
import fs from 'fs';
import { ReGenerateImagePanel } from './ReGenerateImage/ReGenerateImagePanel';
import { pushFileToDevice } from './pushFileToDevice/pushFileToDevice';
import { HiLogViewProvider } from './HiLog/HiLogViewProvider';
import { HiLogService } from './HiLog/HiLogService';

// 检查文件夹是否包含 bundle.json
async function hasBundleJson(folderPath: string): Promise<boolean> {
	const targetFile = path.join(folderPath, 'bundle.json');
	try {
	  await fs.promises.access(targetFile, fs.constants.F_OK);
	  return true;
	} catch {
	  return false;
	}
}

// 装饰器提供程序
class BundleIndicatorProvider implements vscode.FileDecorationProvider {
	private _onDidChange = new vscode.EventEmitter<vscode.Uri[]>();
	readonly onDidChangeFileDecorations = this._onDidChange.event;
  
	// 当需要更新装饰时调用
	refresh(uris: vscode.Uri[]) {
	  this._onDidChange.fire(uris);
	}
  
	// 核心装饰逻辑
	async provideFileDecoration(uri: vscode.Uri): Promise<vscode.FileDecoration | undefined> {
		// 只处理文件系统中的文件/文件夹
		if (uri.scheme !== 'file') {
			return;
		}

	  	const stat = await vscode.workspace.fs.stat(uri);
	  
		// 为 bundle.json 文件提供装饰
		if (stat.type === vscode.FileType.File && path.basename(uri.fsPath) === 'bundle.json') {
			return {
			badge: '📦',
			tooltip: 'Bundle JSON File',
			color: new vscode.ThemeColor('charts.orange')
			};
		}
	  
	    // 为包含 bundle.json 的文件夹提供装饰
		if (stat.type === vscode.FileType.Directory) {

            // 检查是否是build目录
			if (path.basename(uri.fsPath) === 'build') {
				// 检查同级目录是否有.repo文件夹
				const parentDir = path.dirname(uri.fsPath);
				try {
					const repoPath = path.join(parentDir, '.repo');
					const repoStat = await vscode.workspace.fs.stat(vscode.Uri.file(repoPath));
					// 如果.repo文件夹存在，则不装饰
					if (repoStat.type === vscode.FileType.Directory) {
						return undefined;
					}
				} catch {
					// .repo不存在，继续装饰
				}
				
				return {
					badge: '🔨',
					tooltip: 'Build Directory',
					color: new vscode.ThemeColor('charts.green'),
					propagate: false
				};
			}
			
			// 检查是否是out目录
			if (path.basename(uri.fsPath) === 'out') {
				// 检查同级目录是否有.repo文件夹
				const parentDir = path.dirname(uri.fsPath);
				try {
					const repoPath = path.join(parentDir, '.repo');
					const repoStat = await vscode.workspace.fs.stat(vscode.Uri.file(repoPath));
					// 如果.repo文件夹存在，则不装饰
					if (repoStat.type === vscode.FileType.Directory) {
						return undefined;
					}
				} catch {
					// .repo不存在，继续装饰
				}
				
				return {
					badge: '🔨',
					tooltip: 'Out Directory',
					color: new vscode.ThemeColor('charts.green'),
					propagate: false
				};
			}
			
			const hasBundle = await hasBundleJson(uri.fsPath);
			return hasBundle ? {
				badge: '📦',
				tooltip: 'Component Folder with bundle.json',
				color: new vscode.ThemeColor('charts.blue'),
				propagate: false
			} : undefined;
  		}
	  
	  	return undefined;
	}
}

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

	const provider = new BundleIndicatorProvider();
	const watcher = vscode.workspace.createFileSystemWatcher('**/bundle.json');
  
	// 注册装饰器
	context.subscriptions.push(
	  vscode.window.registerFileDecorationProvider(provider)
	);
  
	// 监听 bundle.json 变化
	const refreshParentFolder = (uri: vscode.Uri) => {
	  const parentUri = vscode.Uri.file(path.dirname(uri.fsPath));
	  provider.refresh([parentUri]);
	};
  
	watcher.onDidCreate(refreshParentFolder);
	watcher.onDidDelete(refreshParentFolder);
	
	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "component-compile" is now active!');

	// Register HiLog view provider
	const hiLogViewProvider = new HiLogViewProvider(context.extensionUri);
	context.subscriptions.push(
		vscode.window.registerWebviewViewProvider(
			HiLogViewProvider.viewType,
			hiLogViewProvider
		)
	);

	const hiLogService = HiLogService.getInstance();
	context.subscriptions.push({
		dispose: () => {
			hiLogService.stopDeviceMonitoring();
		}
	});

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with registerCommand
	// The commandId parameter must match the command field in package.json
	context.subscriptions.push(vscode.commands.registerCommand('component-compile.syncCode', (...args: any[]) => {
		syncCode(args);
	}));
	
	context.subscriptions.push(vscode.commands.registerCommand('component-compile.componentCompile', (...args: any[]) => {
		componentCompile(context, args);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('component-compile.prebuild-download-option1', (...args: any[]) => {
		prebuildDownload(args, true);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('component-compile.prebuild-download-option2', (...args: any[]) => {
		prebuildDownload(args, false);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('component-compile.pushFileToDevice', (...args: any[]) => {
		pushFileToDevice(args, context);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('component-compile.showHiLog', (...args: any[]) => {
		// Focus the HiLogViewProvider view
		vscode.commands.executeCommand('hiLogView.focus');
	}));

	context.subscriptions.push(vscode.commands.registerCommand('component-compile.remoteConfiguration', (...args: any[]) => {
		openOrCreateComponentConfigFile();
	}));
}

// This method is called when your extension is deactivated
export function deactivate() {}

/**
 * Opens or creates a componentCompile.json configuration file in the user's home directory
 */
async function openOrCreateComponentConfigFile() {
	const os = require('os');
	const homedir = os.homedir();
	const configFilePath = path.join(homedir, 'componentCompile.json');
	
	// Check if file exists
	if (!fs.existsSync(configFilePath)) {
		// Create file with default content
		const defaultContent = JSON.stringify({ ip: "", port: "" }, null, 2);
		try {
			fs.writeFileSync(configFilePath, defaultContent, 'utf8');
			vscode.window.showInformationMessage('Created componentCompile.json configuration file in your home directory');
		} catch (error) {
			vscode.window.showErrorMessage(`Failed to create configuration file: ${error instanceof Error ? error.message : String(error)}`);
			return;
		}
	}
	
	// Open the file in editor
	const document = await vscode.workspace.openTextDocument(configFilePath);
	await vscode.window.showTextDocument(document);
}
